<?php
/**
 * Created by PhpStorm.
 * User: iamya
 * Date: 2017/11/27
 * Time: 14:46
 */

namespace app\home\controller;


use app\common\MorderModel;
use app\common\MorderNodeModel;
use think\Db;
use think\Exception;
use think\Request;
use think\Validate;

class MorderController extends BaseController
{
    private $userInfo;
    private $orderModel;
    private $orderNodeModel;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->userInfo = $this->getDduser();
        $this->orderModel = new MorderModel();
        $this->orderNodeModel = new MorderNodeModel();

    }

    /**
     * 获取订单列表
     */
    public function index()
    {
        $type = $this->request->param('type', 'now');//获取的类型，now：当前需要负责的。all：全部参与过的
        $data = $this->request->param();
        $map = [];
        switch ($type) {
            case 'now':
                $map['node_charge'] = $this->userInfo['userid'];
                break;
            case 'all':
                $map['charge'] = ['like', '%' . $this->userInfo['userid'] . '%'];
                break;
        }
        if (!empty($data['customer_id'])) {
            $map['customer_id'] = $data['customer_id'];
        }
        if (!empty($data['node_name'])) {
            $map['node_name'] = $data['node_name'];
        }
        if (!empty($data['order_name'])) {
            $map['order_name'] = ['like', '%' . $data['order_name'] . '%'];
        }
        if (!empty($data['order_sn'])) {
            $map['order_sn'] = $data['order_sn'];
        }
        if (!empty($data['order_status'])) {
            $map['order_status'] = $data['order_status'];
        }
        if (!empty($data['is_deleted'])) {
            $map['is_deleted'] = $data['is_deleted'];
        } else {
            $map['is_deleted'] = 0;
        }
        $startTime = $this->request->param('start_time', '1970-01-01 08:00:01');
        $endTime = $this->request->param('end_time', '5138-11-16 17:46:39');
        $map['create_time'] = ['between', [strtotime($startTime), strtotime($endTime)]];
        $list = $this->orderModel->where($map)->paginate(12, false, ['query' => $data]);
        return $this->callBack(0, '', $list);
    }

    /**
     * 获取订单详情
     */
    public function getOrderInfo()
    {
        $orderId=$this->request->param('order_id',0);
        $info=$this->orderModel->where('order_id',$orderId)->find();
        return $this->callBack(0,'',$info);
    }

    /**
     * 增加订单
     */
    public function add()
    {
        $data = $this->request->param();
        $data['create_userid'] = $this->userInfo['userid'];
        if (empty($data['owner_userid'])) {
            $data['owner_userid'] = $this->userInfo['userid'];
        }
        if (empty($data['order_status'])) {
            $data['order_status'] = 0;
        }
        if (!empty($data['business_id'])) {
            $businessInfo=Db::table('business')->where('business_id',$data['business_id'])->find();
            if (empty($businessInfo)){
                return $this->callBack(1,'请选择正确的商机');
            }
            $data['customer_id']=$businessInfo['customer_id'];
        }
        $data['charge'] = $data['owner_userid'];
        $validate = new Validate([
            ['order_name', 'require', '请填写订单名字'],
            ['customer_id', 'require', '请选择客户'],
            ['order_price', 'require', '请输入该订单金额'],
            ['create_userid', 'require', '请先登录'],
            ['owner_userid', 'require', '请指定订单归属人'],
            ['take_time', 'require', '请填写合同生效时间'],
            ['end_time', 'require', '请填写合同预计结束时间'],
            ['order_status', 'require', '请选择合同状态'],
            ['charge', 'require', '请指定负责人'],
            ['node_id', 'require', '请指定操作节点'],
            ['node_charge', 'require', '请指定节点负责人'],
        ]);
        $result = $validate->check($data);
        if (true !== $result) {
            return $this->callBack(1, $validate->getError());
        }
        $nodeInfo = Db::table('node')->where('id', $data['node_id'])->find();
        if (empty($nodeInfo)) {
            return $this->callBack(1, '请指定正确的节点');
        } else {
            $data['node_name'] = $nodeInfo['node_name'];
        }
        $data['order_sn'] = rand_number();
        Db::startTrans();
        try {
            $this->orderModel->data($data)->save();
            $node = [
                [
                    'node_name' => '生成订单',
                    'node_charge' => $this->userInfo['userid'],
                    'order_id' => $this->orderModel->getLastInsID(),
                    'order_sn' => $data['order_sn'],
                    'customer_id' => $data['customer_id'],
                    'business_id' => empty($data['business_id']) ? 0 : $data['business_id'],
                    'node_status' => 1,
                    'node_text' => [],
                    'create_time' => time(),
                    'create_userid' => $this->userInfo['userid']
                ],
                [
                    'node_name'=>$nodeInfo['node_name'],
                    'node_charge'=>$data['charge'],
                    'order_id'=>$this->orderModel->getLastInsID(),
                    'order_sn'=>$data['order_sn'],
                    'customer_id'=>$data['customer_id'],
                    'business_id' => empty($data['business_id']) ? 0 : $data['business_id'],
                    'node_status'=>0,
                    'node_text'=>[],
                    'create_time'=>time(),
                    'create_userid'=>$this->userInfo['userid']
                ]
            ];
            $this->orderNodeModel->saveAll($node);
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            return $this->callBack(2,$e->getMessage());
        }
        return $this->callBack(0,'订单生成成功',$this->orderModel->getLastInsID());
    }

    /**
     * 修改订单
     */
    public function edit()
    {
        $data = $this->request->param();
        $data['create_userid'] = $this->userInfo['userid'];
        if (empty($data['owner_userid'])) {
            $data['owner_userid'] = $this->userInfo['userid'];
        }
        if (empty($data['order_status'])) {
            $data['order_status'] = 0;
        }
        if (!empty($data['business_id'])) {
            $businessInfo=Db::table('business')->where('business_id',$data['business_id'])->find();
            if (empty($businessInfo)){
                return $this->callBack(1,'请选择正确的商机');
            }
            $data['customer_id']=$businessInfo['customer_id'];
        }
        $data['charge'] = $data['owner_userid'];
        $validate = new Validate([
            ['order_id','require','请选择正确的订单'],
            ['order_name', 'require', '请填写订单名字'],
            ['customer_id', 'require', '请选择客户'],
            ['order_price', 'require', '请输入该订单金额'],
            ['create_userid', 'require', '请先登录'],
            ['owner_userid', 'require', '请指定订单归属人'],
            ['take_time', 'require', '请填写合同生效时间'],
            ['end_time', 'require', '请填写合同预计结束时间'],
            ['order_status', 'require', '请选择合同状态'],
        ]);
        $result = $validate->check($data);
        if (true !== $result) {
            return $this->callBack(1, $validate->getError());
        }
        $data['order_sn'] = rand_number();
        Db::startTrans();
        try {
            $this->orderModel->data($data)->save();
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            return $this->callBack(2,$e->getMessage());
        }
        return $this->callBack(0,'订单修改成功',$this->orderModel->getLastInsID());
    }

    /**
     * 删除订单
     */
    public function del()
    {
        $orderId=$this->request->param('order_id',0);
        if ($this->orderModel->where('order_id',$orderId)->save(['is_deleted'=>1,'delete_time'=>time(),'delete_userid'=>$this->userInfo['userid']])){
            return $this->callBack(0,'订单删除成功');
        }else{
            return $this->callBack(2,$this->orderModel->getError());
        }
    }

    /**
     * 设置订单状态
     */
    public function setStatus()
    {
        $data=$this->request->param();
        $validate=new Validate([
            ['order_id','require','请选择订单'],
            ['order_status','require','请选择订单状态'],
        ]);
        $result=$validate->check($data);
        if (true!==$result){
            return $this->callBack(1,$validate->getError());
        }
        if ($this->orderModel->where('order_id',$data['order_id'])->where('charge','like','%'.$this->userInfo['userid'].'%')->setField('order_status',$data['order_status'])){
            return $this->callBack(0,'订单状态设置成功');
        }else{
            return $this->callBack(2,$this->orderModel->getError());
        }
    }

    /**
     * 设置订单节点
     */
    public function setNode()
    {
        $data=$this->request->param();
        $validate=new Validate([
            ['order_id','require','请选择订单'],
            ['node_id','require','请选择节点'],
            ['node_charge','require','请指定节点负责人'],
        ]);
        $result=$validate->check($data);
        if (true!==$result){
            return $this->callBack(1,$validate->getError());
        }
        $nodeInfo=Db::table('node')->where('node_id',$data['node_id'])->find();
        if (empty($nodeInfo)){
            return $this->callBack(1,'请指定正确的节点');
        }
        $orderInfo=$this->orderModel->where('order_id',$data['order_id'])->find();
        if (empty($orderInfo)){
            return $this->callBack(1,'请指定正确的订单');
        }
        $data['node_name']=$nodeInfo['node_name'];
        Db::startTrans();
        try{
            $data['charge']=$orderInfo['charge']+[$data['node_charge']];
            $this->orderModel->data($data)->save();
            $this->orderNodeModel->where(['order_id' => $data['order_id'],'node_status'=>0])->setField('node_status',1);
            $node=
                [
                    'node_name' =>$nodeInfo['node_name'],
                    'node_charge' => $data['node_charge'],
                    'order_id' => $data['order_id'],
                    'order_sn' => $orderInfo['order_sn'],
                    'customer_id' => $data['customer_id'],
                    'business_id' => $orderInfo['business_id'],
                    'node_status' => 0,
                    'node_text' => [],
                    'create_time' => time(),
                    'create_userid' => $this->userInfo['userid']
                ];
            $this->orderNodeModel->data($node)->save();
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            return $this->callBack(2,$e->getMessage());
        }
        return $this->callBack(0,'节点更新成功',$this->orderNodeModel->getLastInsID());
    }

}